<?php
/**
 * Theme Testing and Validation
 * 主题测试和验证功能
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * 主题集成测试类
 */
class WBW_Theme_Testing {
    
    private $test_results = array();
    private $errors = array();
    private $warnings = array();
    
    public function __construct() {
        if (current_user_can('manage_options')) {
            add_action('admin_menu', array($this, 'add_testing_menu'));
            add_action('wp_ajax_wbw_run_tests', array($this, 'ajax_run_tests'));
        }
    }
    
    /**
     * 添加测试菜单
     */
    public function add_testing_menu() {
        add_submenu_page(
            'themes.php',
            'WP Bootstrap Woo 测试',
            '主题测试',
            'manage_options',
            'wbw-testing',
            array($this, 'testing_page')
        );
    }
    
    /**
     * 测试页面
     */
    public function testing_page() {
        ?>
        <div class="wrap">
            <h1>WP Bootstrap Woo 主题测试</h1>
            <p>这个工具将测试主题的各项功能是否正常工作。</p>
            
            <div id="test-controls">
                <button id="run-all-tests" class="button button-primary">运行所有测试</button>
                <button id="run-template-tests" class="button">模板测试</button>
                <button id="run-woocommerce-tests" class="button">WooCommerce测试</button>
                <button id="run-performance-tests" class="button">性能测试</button>
                <button id="run-mobile-tests" class="button">移动端测试</button>
            </div>
            
            <div id="test-results" style="margin-top: 20px;"></div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('#run-all-tests').click(function() {
                runTests('all');
            });
            
            $('#run-template-tests').click(function() {
                runTests('templates');
            });
            
            $('#run-woocommerce-tests').click(function() {
                runTests('woocommerce');
            });
            
            $('#run-performance-tests').click(function() {
                runTests('performance');
            });
            
            $('#run-mobile-tests').click(function() {
                runTests('mobile');
            });
            
            function runTests(testType) {
                $('#test-results').html('<div class="notice notice-info"><p>正在运行测试...</p></div>');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'wbw_run_tests',
                        test_type: testType,
                        nonce: '<?php echo wp_create_nonce('wbw_testing_nonce'); ?>'
                    },
                    success: function(response) {
                        $('#test-results').html(response.data);
                    },
                    error: function() {
                        $('#test-results').html('<div class="notice notice-error"><p>测试运行失败</p></div>');
                    }
                });
            }
        });
        </script>
        <?php
    }
    
    /**
     * Ajax运行测试
     */
    public function ajax_run_tests() {
        if (!wp_verify_nonce($_POST['nonce'], 'wbw_testing_nonce')) {
            wp_die('安全验证失败');
        }
        
        $test_type = sanitize_text_field($_POST['test_type']);
        
        $this->test_results = array();
        $this->errors = array();
        $this->warnings = array();
        
        switch ($test_type) {
            case 'all':
                $this->run_all_tests();
                break;
            case 'templates':
                $this->test_template_files();
                break;
            case 'woocommerce':
                $this->test_woocommerce_integration();
                break;
            case 'performance':
                $this->test_performance();
                break;
            case 'mobile':
                $this->test_mobile_compatibility();
                break;
        }
        
        wp_send_json_success($this->generate_test_report());
    }
    
    /**
     * 运行所有测试
     */
    private function run_all_tests() {
        $this->test_template_files();
        $this->test_woocommerce_integration();
        $this->test_javascript_files();
        $this->test_css_files();
        $this->test_performance();
        $this->test_mobile_compatibility();
        $this->test_security();
    }
    
    /**
     * 测试模板文件
     */
    private function test_template_files() {
        $this->add_test_section('模板文件测试');
        
        $required_templates = array(
            'index.php' => '主页模板',
            'header.php' => '头部模板',
            'footer.php' => '底部模板',
            '404.php' => '404错误页面',
            'woocommerce/archive-product.php' => 'WooCommerce商品列表',
            'woocommerce/single-product.php' => 'WooCommerce单个产品',
            'woocommerce/cart/cart.php' => 'WooCommerce购物车',
            'woocommerce/checkout/form-checkout.php' => 'WooCommerce结账页面',
        );
        
        foreach ($required_templates as $file => $description) {
            $path = get_template_directory() . '/' . $file;
            if (file_exists($path)) {
                $this->add_test_result('✅ ' . $description . ' 存在', 'success');
                
                // 检查模板语法
                if ($this->check_php_syntax($path)) {
                    $this->add_test_result('✅ ' . $description . ' 语法正确', 'success');
                } else {
                    $this->add_test_result('❌ ' . $description . ' 语法错误', 'error');
                }
            } else {
                $this->add_test_result('❌ ' . $description . ' 缺失', 'error');
            }
        }
    }
    
    /**
     * 测试WooCommerce集成
     */
    private function test_woocommerce_integration() {
        $this->add_test_section('WooCommerce集成测试');
        
        // 检查WooCommerce是否激活
        if (class_exists('WooCommerce')) {
            $this->add_test_result('✅ WooCommerce 已激活', 'success');
            
            // 检查主题支持
            if (current_theme_supports('woocommerce')) {
                $this->add_test_result('✅ 主题支持 WooCommerce', 'success');
            } else {
                $this->add_test_result('❌ 主题不支持 WooCommerce', 'error');
            }
            
            // 检查产品画廊支持
            $gallery_features = array('zoom', 'lightbox', 'slider');
            foreach ($gallery_features as $feature) {
                if (current_theme_supports('wc-product-gallery-' . $feature)) {
                    $this->add_test_result('✅ 支持产品画廊 ' . $feature, 'success');
                } else {
                    $this->add_test_result('⚠️ 不支持产品画廊 ' . $feature, 'warning');
                }
            }
            
            // 检查Ajax处理器
            $ajax_handlers = array(
                'wbw_add_to_cart',
                'wbw_remove_cart_item',
                'wbw_add_to_wishlist',
                'wbw_add_to_compare',
                'wbw_quick_view'
            );
            
            foreach ($ajax_handlers as $handler) {
                if (has_action('wp_ajax_' . $handler) || has_action('wp_ajax_nopriv_' . $handler)) {
                    $this->add_test_result('✅ Ajax处理器 ' . $handler . ' 已注册', 'success');
                } else {
                    $this->add_test_result('❌ Ajax处理器 ' . $handler . ' 未注册', 'error');
                }
            }
            
        } else {
            $this->add_test_result('❌ WooCommerce 未激活', 'error');
        }
    }
    
    /**
     * 测试JavaScript文件
     */
    private function test_javascript_files() {
        $this->add_test_section('JavaScript文件测试');
        
        $js_files = array(
            'assets/js/main.js' => '主要脚本',
            'assets/js/woocommerce.js' => 'WooCommerce脚本',
            'assets/js/mobile-responsive.js' => '移动端响应式脚本',
            'assets/js/lazy-load.js' => '图片懒加载脚本',
            'assets/js/wishlist.js' => '愿望清单脚本',
            'assets/js/product-compare.js' => '产品比较脚本',
            'assets/js/product-variations.js' => '产品变体脚本',
        );
        
        foreach ($js_files as $file => $description) {
            $path = get_template_directory() . '/' . $file;
            if (file_exists($path)) {
                $this->add_test_result('✅ ' . $description . ' 存在', 'success');
                
                // 检查文件大小
                $size = filesize($path);
                if ($size > 0) {
                    $this->add_test_result('✅ ' . $description . ' 大小: ' . $this->format_bytes($size), 'success');
                } else {
                    $this->add_test_result('⚠️ ' . $description . ' 文件为空', 'warning');
                }
            } else {
                $this->add_test_result('❌ ' . $description . ' 缺失', 'error');
            }
        }
    }
    
    /**
     * 测试CSS文件
     */
    private function test_css_files() {
        $this->add_test_section('CSS文件测试');
        
        $css_files = array(
            'assets/css/plugin.css' => '插件样式',
            'assets/css/style1.css' => '首页样式1',
            'assets/css/collection.css' => '商品列表样式',
            'assets/css/product-page.css' => '产品页面样式',
            'assets/css/mobile-responsive.css' => '移动端响应式样式',
            'inc/override-styles.css' => 'WooCommerce样式覆盖',
        );
        
        foreach ($css_files as $file => $description) {
            $path = get_template_directory() . '/' . $file;
            if (file_exists($path)) {
                $this->add_test_result('✅ ' . $description . ' 存在', 'success');
                
                $size = filesize($path);
                $this->add_test_result('✅ ' . $description . ' 大小: ' . $this->format_bytes($size), 'success');
            } else {
                $this->add_test_result('❌ ' . $description . ' 缺失', 'error');
            }
        }
    }
    
    /**
     * 测试性能
     */
    private function test_performance() {
        $this->add_test_section('性能测试');
        
        // 检查资源优化设置
        if (_xin('optimize_css', false)) {
            $this->add_test_result('✅ CSS优化已启用', 'success');
        } else {
            $this->add_test_result('⚠️ CSS优化未启用', 'warning');
        }
        
        if (_xin('optimize_js', false)) {
            $this->add_test_result('✅ JavaScript优化已启用', 'success');
        } else {
            $this->add_test_result('⚠️ JavaScript优化未启用', 'warning');
        }
        
        if (_xin('lazy_load_images', true)) {
            $this->add_test_result('✅ 图片懒加载已启用', 'success');
        } else {
            $this->add_test_result('⚠️ 图片懒加载未启用', 'warning');
        }
        
        // 检查CDN设置
        $cdn_mod = _xin('assets_cdn_mod', 'theme');
        if ($cdn_mod !== 'theme') {
            $this->add_test_result('✅ CDN加速已启用', 'success');
        } else {
            $this->add_test_result('⚠️ CDN加速未启用', 'warning');
        }
    }
    
    /**
     * 测试移动端兼容性
     */
    private function test_mobile_compatibility() {
        $this->add_test_section('移动端兼容性测试');
        
        // 检查移动端样式文件
        $mobile_css = get_template_directory() . '/assets/css/mobile-responsive.css';
        if (file_exists($mobile_css)) {
            $this->add_test_result('✅ 移动端响应式样式存在', 'success');
        } else {
            $this->add_test_result('❌ 移动端响应式样式缺失', 'error');
        }
        
        // 检查移动端JavaScript
        $mobile_js = get_template_directory() . '/assets/js/mobile-responsive.js';
        if (file_exists($mobile_js)) {
            $this->add_test_result('✅ 移动端响应式脚本存在', 'success');
        } else {
            $this->add_test_result('❌ 移动端响应式脚本缺失', 'error');
        }
        
        // 检查视口设置
        ob_start();
        wp_head();
        $head_content = ob_get_clean();
        
        if (strpos($head_content, 'viewport') !== false) {
            $this->add_test_result('✅ 视口标签已设置', 'success');
        } else {
            $this->add_test_result('❌ 视口标签缺失', 'error');
        }
    }
    
    /**
     * 测试安全性
     */
    private function test_security() {
        $this->add_test_section('安全性测试');
        
        // 检查主要文件的安全性
        $files_to_check = array(
            'functions.php',
            'inc/template-woo-ajax.php',
            'inc/woocommerce-config.php',
        );
        
        foreach ($files_to_check as $file) {
            $path = get_template_directory() . '/' . $file;
            if (file_exists($path)) {
                $content = file_get_contents($path);
                
                // 检查是否有安全检查
                if (strpos($content, 'ABSPATH') !== false || strpos($content, 'wp_verify_nonce') !== false) {
                    $this->add_test_result('✅ ' . $file . ' 包含安全检查', 'success');
                } else {
                    $this->add_test_result('⚠️ ' . $file . ' 缺少安全检查', 'warning');
                }
            }
        }
    }
    
    /**
     * 检查PHP语法
     */
    private function check_php_syntax($file) {
        $output = array();
        $return_var = 0;
        exec("php -l " . escapeshellarg($file) . " 2>&1", $output, $return_var);
        return $return_var === 0;
    }
    
    /**
     * 格式化字节大小
     */
    private function format_bytes($size, $precision = 2) {
        $units = array('B', 'KB', 'MB', 'GB');
        for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . ' ' . $units[$i];
    }
    
    /**
     * 添加测试部分
     */
    private function add_test_section($title) {
        $this->test_results[] = array(
            'type' => 'section',
            'title' => $title
        );
    }
    
    /**
     * 添加测试结果
     */
    private function add_test_result($message, $type = 'info') {
        $this->test_results[] = array(
            'type' => 'result',
            'message' => $message,
            'status' => $type
        );
        
        if ($type === 'error') {
            $this->errors[] = $message;
        } elseif ($type === 'warning') {
            $this->warnings[] = $message;
        }
    }
    
    /**
     * 生成测试报告
     */
    private function generate_test_report() {
        $html = '<div class="wbw-test-report">';
        
        // 测试摘要
        $total_tests = count($this->test_results);
        $error_count = count($this->errors);
        $warning_count = count($this->warnings);
        
        $html .= '<div class="test-summary">';
        $html .= '<h3>测试摘要</h3>';
        $html .= '<p><strong>总测试项:</strong> ' . $total_tests . '</p>';
        $html .= '<p><strong>错误:</strong> ' . $error_count . '</p>';
        $html .= '<p><strong>警告:</strong> ' . $warning_count . '</p>';
        
        if ($error_count === 0 && $warning_count === 0) {
            $html .= '<div class="notice notice-success"><p>✅ 所有测试通过！</p></div>';
        } elseif ($error_count === 0) {
            $html .= '<div class="notice notice-warning"><p>⚠️ 有一些警告项需要注意</p></div>';
        } else {
            $html .= '<div class="notice notice-error"><p>❌ 发现了一些需要修复的问题</p></div>';
        }
        $html .= '</div>';
        
        // 详细测试结果
        $html .= '<div class="test-details">';
        $html .= '<h3>详细测试结果</h3>';
        
        foreach ($this->test_results as $result) {
            if ($result['type'] === 'section') {
                $html .= '<h4>' . esc_html($result['title']) . '</h4>';
            } else {
                $class = 'test-' . $result['status'];
                $html .= '<p class="' . $class . '">' . esc_html($result['message']) . '</p>';
            }
        }
        
        $html .= '</div>';
        $html .= '</div>';
        
        // 添加样式
        $html .= '<style>
            .wbw-test-report { margin: 20px 0; }
            .test-summary { background: #f9f9f9; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
            .test-success { color: #155724; }
            .test-warning { color: #856404; }
            .test-error { color: #721c24; }
            .test-info { color: #0c5460; }
        </style>';
        
        return $html;
    }
}

// 初始化测试类
new WBW_Theme_Testing();